package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.feign.ShoppingFeign;
import com.cskaoyan.order.feign.UserFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {

    @Autowired
    UserFeign userFeign;


    @Autowired
    ShoppingFeign shoppingFeign;


    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        // 1、检查用户的状态
        Long userId = createOrderContext.getUserId();
        ResponseData responseData = userFeign.userVerifyInfo(userId);
        LinkedHashMap<String, Object> result = (LinkedHashMap<String, Object>) responseData.getResult();
        //UserVerifyInfoDto userVerify = (UserVerifyInfoDto) responseData.getResult();
        String isVerify = (String) result.get("isVerify");
        String isExpire = (String) result.get("isExpire");
        if (isExpire.equals("Y") || isVerify.equals("N")) {
            throw new ValidateException("用户未激活或已过期");
        }


        // 2、检查商品的状态
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        Iterator<CartProductDto> iterator = cartProductDtoList.iterator();
        while (iterator.hasNext()) {
            CartProductDto cartProductDto = iterator.next();
            @NotNull @Min(0) Long productId = cartProductDto.getProductId();
            //Item item = itemMapper.selectByPrimaryKey(productId);

            ResponseData responseData1 = shoppingFeign.itemInfo(productId);
            LinkedHashMap<String, Object> item = (LinkedHashMap<String, Object>) responseData1.getResult();

            Integer status = (Integer) item.get("status");
            if (0 == status) {
                throw new ValidateException("商品已下架！");
            }
            Integer num = (Integer) item.get("num");
            Integer limit_num = (Integer) item.get("limit_num");
            // 3、检查商品的库存 和 限购数量
            if (num < cartProductDto.getProductNum() || limit_num < cartProductDto.getProductNum()) {
                throw new ValidateException("购买数量超过限购数量或者库存告急！");
            }

        }

        return true;
    }
}
